package com.mud.mudcommune.view.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.mud.mudcommune.R;
import com.mud.mudcommune.adapter.CaseAdapter;
import com.mud.mudcommune.adapter.MySpinnerAdapter;
import com.mud.mudcommune.entry.CaseContentResponse;
import com.mud.mudcommune.entry.CaseEntry;
import com.mud.mudcommune.entry.CaseResponse;
import com.mud.mudcommune.entry.TypeItemEntry;
import com.mud.mudcommune.view.fragment.twoLevel.CaseDetailsFragment;
import com.mud.mudcommune.utils.ACache;
import com.mud.mudcommune.utils.LogUtils;
import com.mud.mudcommune.http.ApiService;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class CaseFragment extends Fragment implements View.OnClickListener, Callback<CaseResponse> {
    private static final String TAG = CaseFragment.class.getSimpleName();
    private static CaseFragment fragment = new CaseFragment();
    @BindView(R.id.case_style)
    RadioButton styleBtn;
    @BindView(R.id.case_house)
    RadioButton houseBtn;
    @BindView(R.id.case_space)
    RadioButton spaceBtn;
    @BindView(R.id.case_color)
    RadioButton colorBtn;
    @BindView(R.id.radioGroup)
    RadioGroup group;
    @BindView(R.id.spinner_grid)
    GridView spinnerGridView;
    @BindView(R.id.case_list)
    GridView caseGridView;
    @BindView(R.id.case_back)
    ImageView back_image;
    @BindView(R.id.head_title)
    TextView title;
    @BindView(R.id.loading_layout)
    LinearLayout loadingLayout;
    private List<CaseEntry> caseContentList; // 案例
    private MySpinnerAdapter spinnerAdapter;
    private String typeName;
    private CaseAdapter caseAdapter;
    private List<TypeItemEntry> styleList, houseList, spaceList, colorList, list; //类型
    private Boolean isUnfold = false; // 是否展开，是
    private String curType = null;
    private ACache mCache;
    Unbinder unbinder;

    public static Fragment getInstance() {
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_case, container, false);
        unbinder = ButterKnife.bind(this, view);
        mCache = ACache.get(getActivity());
        // 存储风格、户型、空间、颜色下的当前所选item的position, 默认为 加载全部
        mCache.put("color", "" + 0);
        mCache.put("style", "" + 0);
        mCache.put("house", "" + 0);
        mCache.put("space", "" + 0);

        // 当前所选item的类型id,为-1是显示全部
        mCache.put("styleId", "" + -1);
        mCache.put("houseId", "" + -1);
        mCache.put("spaceId", "" + -1);
        mCache.put("colorId", "" + -1);
        requestDate();
        return view;
    }

    // 请求数据
    private void requestDate() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiService.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiService apiService = retrofit.create(ApiService.class);
        Call<CaseResponse> caseTypeResponse = apiService.getCaseType();
        caseTypeResponse.enqueue(this);
        LogUtils.i(TAG,
                mCache.getAsString("styleId") + ", " +
                        mCache.getAsString("houseId") + ", " +
                        mCache.getAsString("spaceId") + ", " +
                        mCache.getAsString("colorId"));
        Call<CaseContentResponse> caseContentResponse = apiService.getCaseContent(mCache.getAsString("styleId"),
                mCache.getAsString("houseId"),
                mCache.getAsString("spaceId"),
                mCache.getAsString("colorId"));
        caseContentResponse.enqueue(new Callback<CaseContentResponse>() {
            @Override
            public void onResponse(Call<CaseContentResponse> call, Response<CaseContentResponse> response) {
                if (loadingLayout != null) {
                    loadingLayout.setVisibility(View.GONE);
                    if (response.body() != null) {
                        caseContentList = response.body().getCaseContentList();
                        if (null != caseContentList) {
                            caseAdapter = new CaseAdapter(getContext(), caseContentList);
                            caseGridView.setAdapter(caseAdapter);
                        } else {
                            caseAdapter.notifyDataSetChanged();
                        }
                        spinnerGridView.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(Call<CaseContentResponse> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }


    @Override
    public void onViewCreated(View view, @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        title.setText(R.string.rbCase);
        if (list == null) {
            list = new ArrayList<>();
        }
        back_image.setVisibility(View.GONE);
        caseGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (caseContentList != null) {
                    Fragment fragment = CaseDetailsFragment.getInstance();
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", ApiService.TYPE_CASE);
                    bundle.putInt("caseId", caseContentList.get(position).getCaseId());
                    fragment.setArguments(bundle);
                    getFragmentManager().beginTransaction()
                            .hide(CaseFragment.getInstance())
                            .add(R.id.main_frame, fragment)
                            .addToBackStack(null)
                            .commit();
                }
            }
        });
    }

    @OnClick({R.id.case_style, R.id.case_house, R.id.case_space, R.id.case_color})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.case_style:
                list.clear();
                if (styleList != null) {
                    list.addAll(styleList);
                }
                typeName = "style";
                changedData();
                break;
            case R.id.case_house:
                list.clear();
                if (houseList != null) {
                    list.addAll(houseList);
                }
                typeName = "house";
                changedData();
                break;
            case R.id.case_space:
                list.clear();
                if (spaceList != null) {
                    list.addAll(spaceList);
                }
                typeName = "space";
                changedData();
                break;
            case R.id.case_color:
                list.clear();
                if (colorList != null) {
                    list.addAll(colorList);
                }
                typeName = "color";
                changedData();
                break;
        }
    }

    private void changedData() {
        if (typeName.equals(curType) && isUnfold) { // 当前点击的类型，与上次点击的相同。且已经展开了。。隐藏
            spinnerGridView.setVisibility(View.GONE);
            isUnfold = false;
        } else {
            curType = typeName;
            isUnfold = true;
            if (spinnerAdapter == null) {
                spinnerAdapter = new MySpinnerAdapter(getContext(), list, typeName);
                spinnerGridView.setAdapter(spinnerAdapter);
            } else {
                spinnerAdapter.setNotifyDataSetChanged(typeName);
            }
            spinnerGridView.setVisibility(View.VISIBLE);
            spinnerGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mCache.put(typeName, "" + position);
                    spinnerAdapter.notifyDataSetChanged();
                    TypeItemEntry typeItemEntry = list.get(position);
                    LogUtils.i(TAG, typeItemEntry.toString());
                    if ("color".equals(typeName)) {
                        mCache.put(typeName + "Id", typeItemEntry.getColorId() + "");
                    } else if ("house".equals(typeName)) {
                        mCache.put(typeName + "Id", typeItemEntry.getHouseTypeId() + "");
                    } else if ("space".equals(typeName)) {
                        mCache.put(typeName + "Id", typeItemEntry.getSpaceId() + "");
                    } else if ("style".equals(typeName)) {
                        mCache.put(typeName + "Id", typeItemEntry.getStyleId() + "");
                    }
                    requestDate();
                    LogUtils.i(TAG, "typeName: " + typeName + ", position: " + position);
                }
            });
        }

        for (int i = 0; i < group.getChildCount(); i++) {
            RadioButton rdBtn = (RadioButton) group.getChildAt(i);
            if (rdBtn.isChecked() && isUnfold) { // 选中且展开
                rdBtn.setTextColor(getResources().getColor(R.color.subColor));
                Drawable drawable = getResources().getDrawable(R.mipmap.shrink);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                rdBtn.setCompoundDrawables(null, null, drawable, null);
            } else {
                rdBtn.setTextColor(getResources().getColor(R.color.black));
                Drawable drawable = getResources().getDrawable(R.mipmap.unfold);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                rdBtn.setCompoundDrawables(null, null, drawable, null);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void onResponse(Call<CaseResponse> call, Response<CaseResponse> response) {
        if (response.body() != null && response.body().getStatus() == 200) {
            CaseEntry caseEntry = response.body().getCaseEntry();
            styleList = caseEntry.getStyleList();
            houseList = caseEntry.getHouseTypeList();
            colorList = caseEntry.getColorList();
            spaceList = caseEntry.getSpaceList();
            TypeItemEntry typeItemEntry = new TypeItemEntry();
            typeItemEntry.setName("全部");
            typeItemEntry.setStyleId(-1);
            typeItemEntry.setColorId(-1);
            typeItemEntry.setHouseTypeId(-1);
            typeItemEntry.setSpaceId(-1);
            styleList.add(0, typeItemEntry);
            houseList.add(0, typeItemEntry);
            colorList.add(0, typeItemEntry);
            spaceList.add(0, typeItemEntry);
            list.clear();
            if ("color".equals(typeName)) {
                list.addAll(colorList);
            } else if ("house".equals(typeName)) {
                list.addAll(houseList);
            } else if ("space".equals(typeName)) {
                list.addAll(spaceList);
            } else if ("style".equals(typeName)) {
                list.addAll(styleList);
            }

            LogUtils.i(TAG, "案例类型数据请求成功");
        }
    }

    @Override
    public void onFailure(Call<CaseResponse> call, Throwable t) {
        t.printStackTrace();
    }

}
